import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_modular/flutter_modular.dart';
import 'package:thinking/config/_.dart';
import 'package:thinking/entity/_.dart';
import 'package:thinking/service/_.dart';
import 'package:thinking/utils/_.dart';
import 'package:thinking/widget/_.dart';

class PersonalUpdateData extends StatefulWidget {
  @override
  _PersonalUpdateData createState() => _PersonalUpdateData();
}

class _PersonalUpdateData extends State<PersonalUpdateData> {
  late UserData userData;
  late Future<dynamic> _function;
  final _key = GlobalKey<FormState>();

  late TextEditingController _nickController;
  late TextEditingController _pwController;
  late TextEditingController _phoneController;
  late TextEditingController _emailController;
  late TextEditingController _autoGraphController;
  Map<String, dynamic> submitData = {
    'user_HeadImg': '',
    'user_NickName': '',
    'user_Phone': '',
    'user_PassWord': '',
    'user_Email': '',
    'user_AutoGraph':''
  };

  Widget title() {
    return Row(
      children: [
        IconButton(
          onPressed: () {
            Modular.to.pop();
          },
          icon: Icon(Icons.arrow_back),
          color: ColorConfig.WhiteBackColor,
          iconSize: 20,
        ),
        Text(
          '修改资料',
          style: TextStyle(
              color: ColorConfig.WhiteBackColor,
              fontSize: 16,
              fontWeight: FontWeight.bold),
        )
      ],
    );
  }

  @override
  void initState() {
    super.initState();
    _function = future();
  }

  future() async {
    await getUserData();
  }

  Future<void> getUserData() async {
    UserData res = await UserService.getUserData(params: {
      'user_Id': SPreferences().getInt('user_Id'),
      'my_Id': SPreferences().getInt('user_Id')
    });
    userData = res;
    setState(() {
      _nickController = TextEditingController(
          text: userData.userNickName == '暂无' ? '' : userData.userNickName);
      _pwController = TextEditingController(text: userData.userPassWord);
      _phoneController = TextEditingController(text: userData.userPhone);
      _emailController =
          TextEditingController(text: userData.userUserInfo!.userEmail);
      _autoGraphController = TextEditingController(text: userData.userUserInfo!.userAutograph);
      submitData['user_HeadImg'] = userData.userHeadImg!.split('/')[ userData.userHeadImg!.split('/').length-1];
    });
  }

  Future<void> getSubmit() async {
    FocusScope.of(context).requestFocus(FocusNode());
    var simpleCallBack = await showDialog(
      context: context,
      builder: (context) {
        return SimpleDialog(
          title: Text('确认提交？'),
          children: <Widget>[
            Container(
              height: 80,
              alignment: Alignment.center,
              child: Text('提交后,将自动退出登录'),
            ),
            Divider(
              height: 1,
            ),
            TextButton(
              child: Text(
                '确认',
                style: TextStyle(
                    color: ColorConfig.ThemeColor,
                    fontSize: 16,
                    fontWeight: FontWeight.bold),
              ),
              onPressed: () {
                Navigator.of(context).pop('ok');
              },
            ),
            Divider(
              height: 1,
            ),
            TextButton(
              child: Text('取消'),
              onPressed: () {
                Navigator.of(context).pop('cancel');
              },
            ),
          ],
        );
      },
    );

    if (simpleCallBack == 'ok') {
      await UserService.updateUserData(
          params: {...submitData, 'user_Id': SPreferences().getInt('user_Id')});
      await Tool.deleteUserList(isDeleteLogin: true);
      Modular.to.pushNamedAndRemoveUntil('/signUp', (Route route) => false);
    }
  }

  @override
  void dispose() {
    _nickController.dispose();
    _pwController.dispose();
    _phoneController.dispose();
    _emailController.dispose();
    _autoGraphController.dispose();
    super.dispose();
  }

  toolUploadFile(List<ImagePickerEntity> pickedFiles) async {
    List<MultipartFile> filesList = [];
    await Stream<MultipartFile>.fromFutures(pickedFiles
        .map((e) => MultipartFile.fromFile(e.filePath!,
        filename: e.filePath!.substring(
            e.filePath!.lastIndexOf("/") + 1, e.filePath!.length)))
        .toList())
        .forEach((e) {
      filesList.add(e);
    });
    FormData formData = FormData.fromMap({'files': filesList});
    List<ToolUpLoadFileData> res =
    await PublicService.upLoadFile(params: formData);
    setState(() {
      userData.setUserHeadImg = Config.apiUrl['BasePhotoUrl'] +'/dynamic/${res[0].imgUrl}';
      submitData['user_HeadImg'] =  res[0].imgUrl;
    });
  }


  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      behavior: HitTestBehavior.translucent,
      onTap: () {
        FocusScope.of(context).requestFocus(FocusNode());
      },
      child: Scaffold(
        resizeToAvoidBottomInset: false,
        appBar: AppBar(
          backgroundColor: ColorConfig.ThemeColor,
          automaticallyImplyLeading: false,
          elevation: 0,
          title: title(),
        ),
        body: FutureBuilder(
          future: _function,
          builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
            return snapshot.connectionState == ConnectionState.done
                ? Container(
                    child: Form(
                      key: _key,
                      child: Panel(
                        top: 0,
                        child: ListView(
                          physics: BouncingScrollPhysics(),

                          shrinkWrap: true,
                          children: <Widget>[
                            SizedBox(
                              height: 20,
                            ),
                            ImagePickerWidget(
                              imageListLength:1,
                              child: Container(
                                  width: Screen.width(context),
                                  decoration: BoxDecoration(
                                      border: Border(bottom: BorderSide(color: ColorConfig.TextColor,width: 1))
                                  ),
                                  child: Row(
                                    children: [
                                      Text('头像：'),
                                      Expanded(child:Row(
                                        children: [ ClipRRect(
                                          borderRadius: BorderRadius.circular(30),
                                          child: ClipOval(
                                            child: Image.network(
                                              userData.userHeadImg!,
                                              height: Screen.setWidth(48),
                                              width: Screen.setWidth(48),
                                              fit: BoxFit.cover,
                                            ),
                                          ),
                                        ),],
                                      )),
                                      Icon(
                                          Icons.arrow_forward_ios
                                      ),
                                    ],

                                  ),
                                ),
                              onChange:
                                  (List<ImagePickerEntity> pickedFiles) {
                                    toolUploadFile(pickedFiles);
                              },
                            ),
                            SizedBox(
                              height: 20,
                            ),
                            TextFormField(
                                maxLength: 30,
                                controller: _nickController,
                                onSaved: (String? value) {
                                  submitData['user_NickName'] = value;
                                },
                                validator: (String? value) {
                                  return value!.length > 12 ? '昵称过长!' : null;
                                },
                                decoration: InputDecoration(
                                    labelText: '昵称：',
                                    counterText: '',
                                    isDense: true,
                                    fillColor: ColorConfig.ThemeColor,
                                    labelStyle: TextStyle(
                                        color: ColorConfig.ThemeColor),
                                    focusedBorder: UnderlineInputBorder(
                                        borderSide: BorderSide(
                                            color: ColorConfig.ThemeColor)))),
                            SizedBox(
                              height: 20,
                            ),
                            TextFormField(
                                maxLength: 30,
                                controller: _autoGraphController,
                                onSaved: (String? value) {
                                  submitData['user_AutoGraph'] = value;
                                },
                                validator: (String? value) {
                                  return value!.length > 20 ? '签名过长!' : null;
                                },
                                decoration: InputDecoration(
                                    labelText: '个性签名：',
                                    counterText: '',
                                    isDense: true,
                                    fillColor: ColorConfig.ThemeColor,
                                    labelStyle: TextStyle(
                                        color: ColorConfig.ThemeColor),
                                    focusedBorder: UnderlineInputBorder(
                                        borderSide: BorderSide(
                                            color: ColorConfig.ThemeColor)))),
                            SizedBox(
                              height: 20,
                            ),
                            TextFormField(
                                maxLength: 30,
                                controller: _phoneController,
                                onSaved: (String? value) {
                                  submitData['user_Phone'] = value;
                                },
                                validator: (String? value) {
                                  return Tool.isRegExp(value!, Type.Phone)
                                      ? null
                                      : '手机号不正确，请检查!';
                                },
                                decoration: InputDecoration(
                                    labelText: '手机号：',
                                    counterText: '',
                                    isDense: true,
                                    fillColor: ColorConfig.ThemeColor,
                                    labelStyle: TextStyle(
                                        color: ColorConfig.ThemeColor),
                                    focusedBorder: UnderlineInputBorder(
                                        borderSide: BorderSide(
                                            color: ColorConfig.ThemeColor)))),
                            SizedBox(
                              height: 20,
                            ),
                            TextFormField(
                                maxLength: 30,
                                controller: _emailController,
                                onSaved: (String? value) {
                                  submitData['user_Email'] = value;
                                },
                                validator: (String? value) {
                                  return Tool.isRegExp(value!, Type.Email)
                                      ? null
                                      : '邮箱格式不正确，请检查!';
                                },
                                decoration: InputDecoration(
                                    labelText: '邮箱：',
                                    counterText: '',
                                    isDense: true,
                                    fillColor: ColorConfig.ThemeColor,
                                    labelStyle: TextStyle(
                                        color: ColorConfig.ThemeColor),
                                    focusedBorder: UnderlineInputBorder(
                                        borderSide: BorderSide(
                                            color: ColorConfig.ThemeColor)))),
                            SizedBox(
                              height: 20,
                            ),
                            TextFormField(
                                maxLength: 30,
                                obscureText: true,
                                controller: _pwController,
                                onSaved: (String? value) {
                                  submitData['user_PassWord'] = value;
                                },
                                validator: (String? value) {
                                  return Tool.isRegExp(value!, Type.PassWord)
                                      ? null
                                      : '密码不小于8位，需包含数字和大小写字母!';
                                },
                                decoration: InputDecoration(
                                    labelText: '密码：',
                                    counterText: '',
                                    isDense: true,
                                    fillColor: ColorConfig.ThemeColor,
                                    labelStyle: TextStyle(
                                        color: ColorConfig.ThemeColor),
                                    focusedBorder: UnderlineInputBorder(
                                        borderSide: BorderSide(
                                            color: ColorConfig.ThemeColor)))),
                            SizedBox(
                              height: 20,
                            ),
                            TextFormField(
                                maxLength: 30,
                                controller: null,
                                obscureText: true,
                                onSaved: (String? value) {},
                                validator: (String? value) {
                                  return value == _pwController.text
                                      ? null
                                      : '两次密码不相等!';
                                },
                                decoration: InputDecoration(
                                    labelText: '再次输入密码：',
                                    counterText: '',
                                    isDense: true,
                                    fillColor: ColorConfig.ThemeColor,
                                    labelStyle: TextStyle(
                                        color: ColorConfig.ThemeColor),
                                    focusedBorder: UnderlineInputBorder(
                                        borderSide: BorderSide(
                                            color: ColorConfig.ThemeColor)))),
                            SizedBox(
                              height: 30,
                            ),
                            ElevatedButton(
                              style: ButtonStyle(
                                textStyle: MaterialStateProperty.all(
                                    TextStyle(fontSize: 16)),
                                backgroundColor:
                                    MaterialStateProperty.resolveWith((states) {
                                  return states.contains(MaterialState.pressed)
                                      ? ColorConfig.ThemeColor
                                      : Colors.white;
                                }),
                                shape: MaterialStateProperty.all(
                                    RoundedRectangleBorder(
                                        borderRadius: BorderRadius.all(
                                            Radius.circular(8)))),
                                elevation: MaterialStateProperty.all(1),
                                side: MaterialStateProperty.all(BorderSide(
                                  width: 1.0,
                                  color: ColorConfig.ThemeColor,
                                )),
                                foregroundColor:
                                    MaterialStateProperty.resolveWith((states) {
                                  return states.contains(MaterialState.pressed)
                                      ? Colors.white
                                      : ColorConfig.ThemeOtherColor;
                                }),
                              ),
                              child: Text('确认修改'),
                              onPressed: () async {
                                var _state = _key.currentState;
                                if (_state!.validate()) {
                                  _state.save();
                                  await getSubmit();
                                }
                              },
                            )
                          ],
                        ),
                      ),
                    ),
                  )
                : Loading();
          },
        ),
        backgroundColor: ColorConfig.LineColor,
      ),
    );
  }
}
